﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using P2P_Backup.tools.io;

namespace P2P_Backup.connections
{
    public class RemoteFileConnection
    {
        public IPEndPoint endPoint;
        public archive.File file;
        public ProgressReporter Progress;
        private TcpClient tcpClient;
        private Thread fileReceiver;
        private StreamCopy streamCopy;
        

        public RemoteFileConnection(archive.File file,IPEndPoint endPoint)
        {
            this.endPoint = endPoint;
            this.file = file;
            streamCopy = new StreamCopy();
            Progress = new ProgressReporter(this.file, streamCopy);

            tcpClient = new TcpClient();
            tcpClient.Connect(endPoint);

            fileReceiver = new Thread(recieveFile);
            fileReceiver.IsBackground = true;
            fileReceiver.Start();           

            if (file is archive.ArchivedFile)
                P2PBackup.Instance.RemoteBackupFileConnections.Add(this);                
            else
                P2PBackup.Instance.RemoteRestoreFileConnections.Add(this);
        }
        private void recieveFile()
        {            
            Console.WriteLine("Recieving incoming file : {0}", file.Name());
            Progress.Begin();
            Stream output = file.GetWritableStream();
            streamCopy.CopyStream(tcpClient.GetStream(),output,file.Size);
            if (file.Status != archive.TransferStatus.Failed)
            {
                Console.WriteLine("Stored incoming file : {0}", file.Name());
                Progress.Done();
            }
            tcpClient.Close();

            if (this.file is archive.DataFile)
                (this.file as archive.DataFile).DoRestore();
            output.Close();
        } 
    }
}
